package com.example.tbplus14.utils.poi;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import static com.example.tbplus14.utils.html.Html2PDFTest.RESOURCE_PATH;

public class EasyPoiWordUtil {


    public static String baseUrl() {
        try {
            URL imgBaseUrl = new ClassPathResource(RESOURCE_PATH).getURL();
            return imgBaseUrl.getPath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception{
        String wordPath = easyExportWord1();
        String pdfPath = baseUrl() + "static/"; ;//生成临时文件存放地址
        word2Pdf(pdfPath + "111111.pdf", wordPath);
    }

    /**
     * 获取license
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream license = EasyPoiWordUtil.class.getClassLoader().getResourceAsStream("license.xml");
            if (license == null) {
                System.out.println("License file not found in classpath.");
                return false;
            }
            License asposeLic = new License();
            asposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * word转pdf
     * @param pdfFilePath pdf生成路径
     * @param wordFilePath  word文件路径
     */
    public static void word2Pdf(String pdfFilePath, String wordFilePath) {
        // 检查 License
        if (!getLicense()) {
            System.out.println("License 验证失败，转换可能带有水印！");
        }

        // 检查输入文件是否存在
        File inputFile = new File(wordFilePath);
        if (!inputFile.exists()) {
            System.out.println("输入文件不存在" + wordFilePath);
            return;
        }
        // 确保输出目录存在
        File outputFile = new File(pdfFilePath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs(); // 创建所有缺失的目录
        }

        // 自动关闭资源（Java 7+）
        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(pdfFilePath)) {

            Document doc = new Document(fis);
            doc.save(fos, SaveFormat.PDF);
            System.out.println("PDF 转换成功: " + pdfFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String easyExportWord1() throws Exception {
        Map<String, Object> params = new HashMap<>();
        String templatePath = baseUrl() + "/static/font/easyTemp.docx"; //模板路径

        //简单渲染文本
        params.put("title","2021年暑期放假通知");
        params.put("first","2021年暑期放假通知");
        params.put("second","2021年暑期放假通知2021年暑期放假通知2021年暑期放假通知2021年暑期放假通知2021年暑期放假通知2021年暑期放假通知");


        ImageEntity image = new ImageEntity();
        image.setHeight(122);
        image.setWidth(246);
        image.setUrl(baseUrl() + "bingtu.png"); //url路径
        //image.setData(out.toByteArray()); //字节流读取
        //设置读取图片方式(必须)
        image.setType(ImageEntity.URL);
        //表格外添加简单图片
        params.put("img1", image);

        ImageEntity image1 = new ImageEntity();
        image1.setHeight(122);
        image1.setWidth(246);
        image1.setUrl(baseUrl() + "huantu.png"); //url路径
        //image.setData(out.toByteArray()); //字节流读取
        //设置读取图片方式(必须)
        image1.setType(ImageEntity.URL);
        //表格外添加简单图片
        params.put("img2", image1);

        //渲染表格
        List<Map<String, Object>> jobs = new ArrayList<>();

        for (int i = 0; i < 50; i++) {
            Map<String, Object> job = new HashMap<>();
            job.put("name", "洪不亮-" + i);
            job.put("sex", "男:" + i);
            job.put("dept", "开发部:" + i);
            //表格内循环添加图片(easypoi 4.3以后才支持,不然只能打印出ImageEntity的内存地址)
            job.put("img", "" + i);

            jobs.add(job);
        }
        //添加
        params.put("jobs", jobs);

        String temDir = baseUrl() + "static"; ;//生成临时文件存放地址
        //生成文件名
        Long time = new Date().getTime();
        // 生成的word格式
        String formatSuffix = ".docx";
        // 拼接后的文件名
        String fileName = time + formatSuffix;//文件名  带后缀
        //导出word
        System.out.println(JSONObject.toJSONString(params));
        return exportWord(templatePath, temDir, fileName, params);
    }


    /**
     * 导出word
     * <p>第一步生成替换后的word文件，只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     * 模版变量中变量格式：{{foo}}
     * @param templatePath word模板地址
     * @param temDir 生成临时文件存放地址
     * @param fileName 文件名
     * @param params 替换的参数
     */
    public static String exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) {

        if (!temDir.endsWith("/")){
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            fos.flush();
            fos.close();
            return tmpPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            delFileWord(temDir,fileName);//这一步看具体需求，要不要删
        }
        return null;
    }

    /**
     * 删除零时生成的文件
     */
    public static void delFileWord(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        File file1 = new File(filePath);
        file.delete();
        file1.delete();
    }





}
